package com.projectplace.GUI.Database;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;

import android.util.Log;
import com.projectplace.GUI.Callback.InternalCacheCallback;


/**
 * Saves your project's to SDCard 
 */
public class SaveToCache extends Thread {
	
	private static FileOutputStream fos;
	private Context context;
	private final static String LOG_TAG = "SaveToCache";
	private InternalCacheCallback callback;
	private String fileName;
	private String data;
	
	
	public SaveToCache(Context context,String fileName,String data,InternalCacheCallback internalCacheCallback){
		this.context = context;
		this.callback = internalCacheCallback;
		this.fileName = fileName;
		this.data = data;

	}
	
	public void run(){
		if(data != null){
			try {
				
				fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
				fos.write(data.getBytes());
				fos.close();
				callback.onSuccess("Success saving file: " +fileName);
			} catch (FileNotFoundException e) {
				callback.onFail(new Error("FileNotFoundException " +fileName));
				Log.d(LOG_TAG, "FileNotFoundException");
				e.printStackTrace();
			} catch (IOException e) {
				callback.onFail(new Error("IOException " +fileName));
				Log.d(LOG_TAG, "IOException");
				e.printStackTrace();
			} 
		}else{
			callback.onFail(new Error("Data is null"));
		}
	}
}
